<script setup>
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { artEditService, artPublishService, artGetDetailService } from '@/api/article.js'
import axios from 'axios'
import { baseURL } from '@/utils/request.js'
import { i18n } from "@/i18n/index.js";

const { t } = i18n.global
const visibleDrawer = ref(false)

const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}
const formModel = ref({ ...defaultForm })

const formRef = ref()
const editorRef = ref() //编辑器的ref

const open = async (row) => {
  visibleDrawer.value = true
  if (row.id) {
    console.log('编辑回显')
    const res = await artGetDetailService(row.id)
    formModel.value = res.data.data
    imgUrl.value = baseURL + formModel.value.cover_img
    // 提交给后台，需要的是 file 格式的，将网络图片，转成 file 格式
    // 网络图片转成 file 对象, 需要转换一下
    formModel.value.cover_img = await convertImageUrlToFile(imgUrl.value)
  } else {
    formModel.value = { ...defaultForm }
    imgUrl.value = ''
    // 富文本编辑器要设置的话，最好是去官网看
    editorRef.value.setHTML('')
  }
}

async function convertImageUrlToFile(imageUrl) {
  try {
    // 使用axios获取图片的响应数据
    const response = await axios.get(imageUrl, {
      responseType: 'blob', // 指定响应类型为blob
    });

    // 创建一个Blob对象，类型为image/png，你也可以根据实际情况设置为其他类型
    const blob = new Blob([response.data], { type: 'image/png' });

    // 将Blob对象转换为File对象
    const file = new File([blob], 'filename.png', { type: 'image/png' });

    // 返回File对象
    return file;
  } catch (error) {
    // 错误处理
    console.error('转换图片为File对象失败:', error);
    throw error;
  }
}

const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

// 发布文章
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  // 将已发布还是草稿状态，存入 state
  formModel.value.state = state

  // 转换 formData 数据
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }

  if (formModel.value.id) {
    await artEditService(fd)
    ElMessage.success(t('message.EditSuccess'))
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    // 添加请求
    await artPublishService(fd)
    ElMessage.success(t('message.AddSuccess'))
    // 关弹窗
    visibleDrawer.value = false
    // 通知到父组件添加成功了
    emit('success', 'add')
  }
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visibleDrawer" :title="formModel.id ? t('message.EditArticle') : t('message.AddArticle')"
    direction="rtl" size="50%">
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item :label="$t('message.ArticleTitle')" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>

      </el-form-item>
      <el-form-item :label="$t('message.ArticleCategory')" prop="cate_id">
        <channel-select v-model="formModel.cate_id" style="width: 100%;"></channel-select>
      </el-form-item>

      <el-form-item :label="$t('message.ArticleCover')" prop="cover_img">
        <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false" :on-change="onUploadFile">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item :label="$t('message.ArticleContent')" prop="content">
        <div class="editor">
          <quill-editor theme="snow" ref="editorRef" v-model:content="formModel.content" contentType="html">
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
        <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
